'''
抗癌卫士2018
'''
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import urlencode
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "抗癌卫士2018"
    # 生产产品信息
    def genProductInfo(self):
        plan = {

            # 年龄段
            "year":[str(i) for i in range(0,71)],
            #性别
            "gender":["M","F"],
            #有无社保
            "socialSec":["Y","N"],
            # 保额
            "money":["2000000"],
            # 期限
            "expire":["1年"],
            #计划
            "plan":[
                "计划A",
                "计划B",
                "计划C"
            ]

        }
        for v in product(plan["year"],plan["gender"],plan["socialSec"],plan["money"],plan["plan"]):

           if v[3] == "计划A":

               introduce = \
                   "二级或二级以上公立医院普通部"


           elif v[3] == "计划B":

               introduce = \
                   "二级或二级以上公立医院普通部"


           else:
               introduce = \
                   "二级或二级以上公立医院普通部+特需部"

           # 写入数据库
           # print(domain[self.name]["insert_sql"].format(v[0], v[1], v[2], v[3], v[4], introduce))
           self.mysql.cursor.execute(

                domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],v[4],introduce))
           self.mysql._conn.commit()
           print(   domain[self.name]["insert_sql"].format( v[0],v[1],v[2],v[3],v[4],introduce))

    #执行爬虫
    def requestJson(self,dt=None):


        if dt["plan"] == "计划A":

            code = "01"

        elif dt["plan"] == "计划B":

            code = "02"

        else:

            code = "03"

        data = {
            "productId": "kaws2018",
            "birthDate": "{year}-02-07".format( year = str(2019-int(dt["year"]))),
            "genderCode": dt["gender"],
            "coverageLevel": code,
            "coverageAmount": "2000000",
            "paymentModeCode": "5",
            "coverageUnits": "1",
            "periodMonth": "12",
            "periodDay": "0",
            "socialSecurity": dt["socialSec"]
        }
        payload = urlencode( data ).replace("+","")
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200:

            price = Helper.decimalParse( r.text )

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("/*任务更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            dt = self.mysql.randTask( self.name )

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
